package client;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Connector implements Runnable {
	Socket requestSocket;
	Scanner scanner = new Scanner(System.in);
	Queue<ServerSocket> socketQueue = new LinkedList<>();

	ObjectOutputStream out;
	String loginName;

	public Connector(String clientName) {
		loginName = clientName;
		}

	public void run() {

		try {
			boolean isConnected = false;
			while (!isConnected) {
				try {
					requestSocket = new Socket("localhost", 2013);
					System.out.println("Connected to localhost in port 2013");
					isConnected = true;
				} catch (UnknownHostException unknownHost) {
					System.err
							.println("You are trying to connect to an unknown host!");
				} catch (ConnectException connectionException) {
					System.err
							.println("Server is not ready, reconnect in 10 seconds ... ");
					try {
						Thread.sleep(10000);
					} catch (InterruptedException e) {
					}

				} catch (IOException ioException) {
					ioException.printStackTrace();

				}
			}
			
			// RUN SocketReader and SocketWriter
			new Thread(new SocketReader(requestSocket)).start();
			new SocketWriter(requestSocket, loginName).run();
			
			System.out.println("Connector quit");
			
		} finally {
			try {
				requestSocket.close();
			} catch (IOException ioException) {
				System.err.println("Can't close the socket.");
			}
		}

	}



}
